package com.dq.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dq.commonutils.jwt.JwtUtil;
import com.dq.commonutils.pojo.DqException;
import com.dq.commonutils.vo.Result;
import com.dq.order.entity.Order;
import com.dq.order.service.OrderService;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * TOrder-API
 * @author Dq
 * @since 2022-08-17 15:16:03
 */
@RestController
@RequestMapping("order/api")
// @CrossOrigin
public class OrderController {
    @Autowired
    private OrderService orderService;

    /**
     * 生成课程订单 返回订单id
     * @return
     */
    @PostMapping("createOrder/{courseId}")
    public Result createOrder(@RequestHeader("Authorization") String token,@PathVariable("courseId") String courseId){
        Map<String, Object> map = JwtUtil.checkToken(token);
        String userId = (String) map.get("userId");
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(token)){
            throw new DqException(20001,"支付参数状态异常，请检查！");
        }
        //填入token中携带的userId  创建一个订单号
        String orderNo=orderService.createOrder(courseId,userId);

        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("orderNo",orderNo);
        return Result.success(resultMap);
    }


    /**
     * 根据订单号返回支付的详细信息
     * @param orderNo
     * @return
     */
    @PostMapping("getOrderInfo/{orderNo}")
    public Result getOrderInfo(@PathVariable("orderNo") String orderNo){
        Order order=orderService.getOrderInfoById(orderNo);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("orderInfo",order);
        return Result.success(resultMap);
    }

    /**
     * 根据课程id 用户id查询此课程是否已经被该用户购买
     * @param courseId
     * @param memberId
     * @return
     */
    @GetMapping("isBuy/{courseId}/{memberId}")
    public Result isBuyThisCourse(@PathVariable("courseId") String courseId,
                                  @PathVariable("memberId") String memberId){
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper
                .eq(Order::getCourseId,courseId)
                .eq(Order::getMemberId,memberId)
                .eq(Order::getStatus,1);
        int count = orderService.count(orderLambdaQueryWrapper);
        if (count>0){
            return Result.success(true);
        }else {
            return Result.error(20001,"");
        }
    }
}